package top.dancun.eascourse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import top.dancun.common.utils.PageUtils;
import top.dancun.common.utils.Query;
import top.dancun.eascourse.dao.ExaminationArrangementDao;
import top.dancun.eascourse.entity.ExaminationArrangementEntity;
import top.dancun.eascourse.entity.StudentEntity;
import top.dancun.eascourse.feign.service.BaseInfoFeignService;
import top.dancun.eascourse.feign.service.StudentFeignService;
import top.dancun.eascourse.service.ExaminationArrangementService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("examinationArrangementService")
public class ExaminationArrangementServiceImpl extends ServiceImpl<ExaminationArrangementDao, ExaminationArrangementEntity> implements ExaminationArrangementService {

    @Autowired
    private StudentFeignService studentFeignService;

    @Autowired
    private BaseInfoFeignService baseInfoFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> pageInfo,Map<String ,String > params) {
        IPage<ExaminationArrangementEntity> page = new Query<ExaminationArrangementEntity>().getPage(pageInfo);
        LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ExaminationArrangementEntity.class)
                .eq(StringUtils.isNotBlank(params.get("roomId")),
                        ExaminationArrangementEntity::getRoomId,
                        params.get("roomId"))
                .eq(StringUtils.isNotBlank(params.get("semester")),
                        ExaminationArrangementEntity::getSemester,
                        params.get("semester"))
                .eq(StringUtils.isNotBlank(params.get("courseId")),
                        ExaminationArrangementEntity::getCourseId,
                        params.get("courseId"))
                .eq(StringUtils.isNotBlank(params.get("studentId")),
                        ExaminationArrangementEntity::getStudentId,
                        params.get("studentId"));
                page = baseMapper.list(wrapper,page);

        List<String> stids = new ArrayList<>();
        List<Integer> roomIdList = new ArrayList<>();
        //获取所有学生id
        page.getRecords().forEach(e->{
            stids.add(e.getStudentId());
            roomIdList.add(e.getRoomId());
        });
        //添加学生信息
        if(stids.size()!=0){
            Map<Integer,String> roomMap = baseInfoFeignService.listRoomByIds(roomIdList);
            PageUtils studentPage = studentFeignService.getByIds(new HashMap<String,String>(),stids,new ArrayList<>());
            List<StudentEntity> studentList = (List<StudentEntity>) studentPage.getList();
            page.getRecords().forEach(e->{
                for(StudentEntity student :studentList){
                    if (student.getSid().equals(e.getStudentId())){
                        e.setStudentName(student.getName());
                        break;
                    }
                }
                e.setRoomName(roomMap.get(e.getRoomId()));
            });
        }



        return new PageUtils(page);
    }

    /**
     * 考试安排
     * @param params
     */


    @Override
    @Transactional
    public void arrangment(Map<String, String> params) throws Exception {
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();

        String startStu = params.get("startStu");
        String courseId = params.get("courseId");
        String endStu = params.get("endStu");
        String roomId = params.get("roomId");
        String invigilator =  params.get("invigilator");
        String time = params.get("time");
        String semester = params.get("semester");
        Integer setNumber = 1;
        try {
            //TODO 远程获取学生（通过排序获取该学号区间的所有学生）列表迭代插入
            while (Integer.parseInt(startStu)<=Integer.parseInt(endStu)){
                ExaminationArrangementEntity examinationArrangement = new ExaminationArrangementEntity();
                examinationArrangement.setCourseId(Long.valueOf(courseId));
                examinationArrangement.setRoomId(Integer.parseInt(roomId));
                examinationArrangement.setStudentId(startStu);
                examinationArrangement.setTime(time);
                examinationArrangement.setInvigilator(invigilator);
                examinationArrangement.setSeatNumber(setNumber);
                examinationArrangement.setSemester(semester);
                // 插入前检查是否已经有人
                Integer hasnull = lambdaQuery().eq(ExaminationArrangementEntity::getRoomId,roomId)
                        .eq(ExaminationArrangementEntity::getSeatNumber,setNumber)
                        .eq(ExaminationArrangementEntity::getSemester,semester).list().size();
                this.baseMapper.insert(examinationArrangement);
                if( hasnull!=0){
                    throw new Exception();
                }
                startStu = String.valueOf(Integer.parseInt(startStu)+1);
                setNumber+=1;
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            throw new Exception();
        }



    }

}